<script setup>
import { ref,defineProps ,defineEmits} from 'vue'
import {UploadFilled} from "@element-plus/icons-vue";
import {ElMessage, genFileId} from "element-plus";
import {listResource, uploadResource} from "../../../api/course/course.js";
import {isPermission} from "../../../utils/utils.js";

// 直接从持久化存储获取
const courseId=localStorage.getItem("courseId");
// 是否显示弹窗
const isUpload = ref(false);
// 获取父组件的值
const prop=defineProps(["isUpload"]);
// 定义引用和响应式数据
const uploadRef = ref(null)
// 文件
const file= ref()
// 赋值
isUpload.value=prop.isUpload;
// 关闭弹窗
const emit=defineEmits(["close","search"]);


// 点击取消
const handleCancel=()=>{
  emit('close');
  isUpload.value=false;
  file.value=null;
}

// 上传文件
const handleUpload=async ()=>{
  if(file.value==null)
    ElMessage.error("请选择文件");
  // console.log(file.value)
  const formData = new FormData();
  // 非常神奇的写法,但是就是这么写的

  formData.append('file', file.value.raw);
  // 发送请求
  await uploadResource(courseId,formData).then(res=>{
    ElMessage.success("上传文件成功");
    emit('close');
    emit('search');
  })
}



// 处理文件选择事件
const handleFileChange = (files) => {
  file.value = files;
};

</script>

<template>
  <!--上传资源-->
  <el-dialog v-model="isUpload" title="上传资源" width="500" align-center v-if="isPermission(2)">
    <el-upload
        ref="uploadRef"
        class="upload-demo"
        action="#"
        :auto-upload="false"
        drag
        :on-change="handleFileChange"
        :file-list="file ? [file] : []"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        将文件拖放到此处或<em>点击上传</em>
      </div>
    </el-upload>

    <!--    底部-->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleUpload">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>


</template>

<style scoped lang="less">

</style>